package com.domain.cumanager;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

public class CURegistrator extends Thread{

	private boolean m_shouldRun;
	private int m_registratorPort;
	private CUStubsHolder m_cuStubsHolder;
	private ServerSocket m_registrationServerSocket = null;
	private static Logger s_logger;

	public CURegistrator(CUStubsHolder cuStubsHolder) {
		super("CURegistrator");
		s_logger = Logger.getLogger(CURegistrator.class);
		m_cuStubsHolder = cuStubsHolder;
		m_registratorPort = 4444;
		m_shouldRun = true;
	}

	public void run(){		
		while(m_shouldRun){
			if(m_registrationServerSocket == null){
				try {
					m_registrationServerSocket = new ServerSocket(m_registratorPort);
					s_logger.info("Ready on port :" + m_registratorPort);
				} catch (IOException e) {
					s_logger.fatal("Could not listen on port: " + m_registratorPort);
					//System.exit(1);
					break;
				}				
			}
			Socket cuStubSocket = null;
			try {
				cuStubSocket = m_registrationServerSocket.accept();
				s_logger.info("New CU accepted from : " + 
						cuStubSocket.getInetAddress().getCanonicalHostName() + 
						":" + cuStubSocket.getPort());
				m_cuStubsHolder.addCUStub(cuStubSocket);
			} catch (IOException e) {
				s_logger.fatal("Accept failed.");
				//System.exit(1);
			}		     			
		}		
		try {
			m_registrationServerSocket.close();
		} catch (IOException e) {
			s_logger.fatal("Failed to close server socket");
			//e.printStackTrace();
		}
	}

}
